/**
 * Created by Administrator on 2017/3/21.
 */
import React, {Component,Fragment} from 'react';
import {
  Form, Input, Radio, Select, Icon,
  Upload, TreeSelect, Button,
} from 'antd';
import {connect} from 'dva';
import moment from 'moment'
import request from '@/utils/request';
import ReactDataGrid from "react-data-grid";
import Loading from "@/components/Loading";
import find from "lodash/find";
const FormItem = Form.Item;
const { TextArea } = Input;
const RadioGroup = Radio.Group;
const Option = Select.Option;
const TreeNode = TreeSelect.TreeNode;
@connect(({ inner_address_book, loading, global }) => ({
  inner_address_book,
  global,
  loading: loading.models.inner_address_book,
}))
class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      fileList:[],
      data:[],
      loading:false,
      searchParams:{
        username:this.props.username?this.props.username:'',
        per_page:500,
        selectedRowKeys:[]
      }
    };
  }

  componentDidMount() {
    this.handleSearch(this.state.searchParams)
  }
  renderTreeNodes = data =>
    data.map((item,index) => {

      if (item.children.length>0) {
        return (
          <TreeNode value={item.id} title={item.name} key={item.id+index} >
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode  value={item.id}   key={item.id+index}  title={item.name}  />;
    });

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    const {
      searchParams
    } = this.state;
    return (
      <Form layout="inline" className="search-form">
        <FormItem label="账号名称">
          {getFieldDecorator('username', {
            initialValue: searchParams.username,
          })(<Input style={{ width: '150px' }} placeholder="请输入" onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>

        </FormItem>

      </Form>
    );
  }
  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      username: '',
      page: 1,
      per_page: 300,
    });
  };
  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    this.setState({
      loading:true
    })
    const that = this;
    const { dispatch } = this.props;
    request(`/search_users`, {
      method: 'GET',
      params:{
        ...values
      }
    }).then((response)=> {
      console.log('all_structures', response)
      if(response.status===200){
        that.setState({
          data:response.data.data,
          loading:false
        })
      }
    })

  };
  keyPress = (e) => {
    let theEvent = e || window.event;
    let code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code === 13) {
      e.preventDefault();
      console.log('key press');
      const { form } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;

        this.handleSearch({
          page: 1,
          per_page: 300,
          ...fieldsValue,
        });

      });
    }
  };
  renderObserve = (val) => {
    let type = '';
    let color = '';
    let text = '';
    switch (val) {
      case -1:
        type = 'close-circle', color = '#eb2f96', text = '禁用';
        break;
      case 1:
        type = 'check-circle', color = '#52c41a', text = '启用';
        break;
      default:
        break;
    }
    return <Fragment> <Icon type={type} theme="twoTone" className="table-icon" twoToneColor={color}/>{text}</Fragment>;
  };
  render() {
    const data=this.state.data;
    const selectedRowKeys=this.state.selectedRowKeys
    const defaultColumnProperties = {
      resizable: true,
    };
    const that=this;
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          return <p className={'index'}>{(event.value + 1)}</p>;
        },
      },
      {
        name: '账号登录名称',
        width: 120,
        key: 'username',
        frozen: true,
      },
      {
        name: '所属角色',
        width: 150,
        key: 'role_name',
      },
      {
        name: '状态',
        width: 100,
        key: 'status',
        formatter: (event) => {
          return this.renderObserve(event.value);
        },
      },
      {
        name: '是否营业员',
        width: 150,
        key: 'revenuer',
        formatter: (event) => {
          let type = '';
          let color = '';
          let text = '';
          switch (Number(event.value)) {
            case -1:
              type = 'close-circle', color = '#eb2f96', text = '否';
              break;
            case 1:
              type = 'check-circle', color = '#52c41a', text = '是';
              break;
            default:
              break;
          }
          return <Fragment> <Icon type={type} theme="twoTone" className="table-icon" twoToneColor={color}/>{text}
          </Fragment>;

        },
      },
      {
        name: '创建时间',
        width: 160,
        key: 'created_at',
      },
      {
        name: '操作',
        width: 120,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          <Button
            className={'btn-cyan'}
            type="primary"
            size="small"
            icon="select"
            onClick={(e) => {
              this.props.selectUser(event.row)
              this.setState({
                editRecord: event.row,

                detailModal: true,
              });
            }
            }
          >选择
          </Button>
        </Fragment>
      }
    ].map(c => ({ ...defaultColumnProperties, ...c }));
    const loading=this.state.loading
    return (
      <div>
        <div className="table-page">
          <div className="table-condition">{this.renderSimpleForm()}</div>
          <div className={'table-data-content'}>
            <ReactDataGrid
              columns={columns}
              rowGetter={i => {
                return { ...data[i], _index: i };
              }}
              rowsCount={data.length}
              minHeight={500}
              rowSelection={{
                showCheckbox: false,
                enableShiftSelect: true,
                selectBy: {
                  indexes: selectedRowKeys,
                },
              }}
              onRowClick={
                (row) => {
                  that.setState({
                    selectedRowKeys:[row]
                  })
                }
              }

            />
            {
              loading && <Loading/>
            }
          </div>


        </div>
      </div>)
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default AddPoliciesFormWrap;

